use std::thread;
use std::sync::mpsc;
use std::sync::Arc;
usr std::sync::Mutex;
struct Worker{
    id:usize,
    thread:thread::JoinHandle<()>,
}
impl Worker{
    // fn new (id:usize)->Worker{
    //     let thread=thread::spawn(move || {
    //     });
    //         Worker{
    //             id,thread
    //         }
    // }
    // fn new (ide:usize,receiver:mpsc::Receiver<Job>)->{
    fn new (ide:usize,receiver:Arc<Mutex<mpsc::Receiver<Job>>>)->{
            
        let thread=thread::spawn(move || {
               
            loop{
                let jon=receiver.lock().unwarp().recv().unwarp();
                println!("Worker {} got a job",id);
                job();
            }

        });
            Worker{
                id,thread
            }
    }
}
struct Job;
type job =Box<dyn FnOnce()+Send+'static>;
pub struct ThreadPool{
   // threads:Vec<thread::JoinHandle<()>>
   workers:Vec<Worker>,
   sender:mpsc::Sender<Job>
}
impl ThreadPool{
    pub fn new(size:usize)->ThreadPool{
        assert!(size>0);
       // let mut threads=Vec::with_capacity(size);
       let mut workers=Vec::with_capacity(size);
       let (sender,receiver)=mpsc::channel();
       let receiver=Arc::new(Mutex::new(receiver));//线程安全
       // for _ in 0..size{
            // let handle=thread::spawn(move || {
                
            // });
            //创建线程时需要传入必报，此时还不知道，怎么办？
           // threads.push(handle)
       // }

       for _ in 0..size{
        //    workers.push(Worker::new(id));
           workers.push(Worker::new(id,Arc::clone(&receiver)) ;

       }



        ThreadPool{
            threads,
            sender
        }

    }
    pub fn excute<F>(&self,f:F)
        where F:FnOnce()+Send+'static {
            let job=Box::new(f);
            self.sender.send(job).unwarp();
    }
}
